const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

const db = cloud.database();
const _ = db.command;

const MONTH_OFFSET = 30 * 24 * 60 * 60 * 1000;

/// (limit = 20, dateSkip = Date.now(), duration = MONTH_OFFSET, listOnlyOpen = true) -> [ Record ]@contract(this.length <= limit)
exports.main = async (event) => {
  const wxContext = cloud.getWXContext();
  const openId = wxContext.OPENID;
  const limit = event.limit || 20;
  const dateSkip = event.dateSkip || Date.now();
  const duration = event.duration || MONTH_OFFSET;
  const dateOffset = dateSkip - duration;
  const listOnlyOpen = event.hasOwnProperty('listOnlyOpen') ? event.listOnlyOpen : true;

  let query = {
    borrowTime: _.gt(dateOffset).lt(dateSkip),
  };

  if (openId) {
    query['openid'] = openId;
  }

  if (listOnlyOpen) {
    query['isOpen'] = true;
  }

  const result = await db.collection('records')
                        .aggregate()
                        .match(query)
                        .lookup({
                          from: 'books',
                          localField: 'book',
                          foreignField: '_id',
                          as: 'book'
                        }).limit(limit)
                        .sort({
                          expectedReturnTime: -1
                        }).end();

  result['data'] = result.list;

  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    env: wxContext.ENV,
    result: result
  };
}
